//
//  HJMainTabBar.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/22.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit

class HJMainTabBar: UITabBar {

    
    var composeClosure: (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //把composeBtn添加到tabbar
        addSubview(composeBtn)
        //添加点击事件
        composeBtn.addTarget(self, action: #selector(composeBtnDidClick), for: .touchUpInside)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //点击composeBtn按钮调用的事件
    
    /*
     按钮点击事件的方法我们不希望外部可以调用,所以把他变成私有方法
    但是Swift中默认给继承自NSObject的类的实例化对象的 非私有属性和方法添加@objc
     而私有方法是没有@objc这个标记的
     该标记是告诉系统对运行方法可见的,所以要加一个@objc
    */
    
    @objc private func composeBtnDidClick() {
        
        //应该将用户的点击事件交给控制器来处理
        composeClosure?()
    }
    
    
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let btnW = self.frame.width / 5
        let btnH = self.frame.height
        var index = 0
        for subview in subviews {
            //因为UITabBarButton是系统的,所以一定有这个类
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subview.frame = CGRect(x: CGFloat(index) * btnW, y: 0, width: btnW, height: btnH)
                index += (index==1) ? 2 : 1
 
            }
        }
       // composeBtn.frame = CGRect(x: self.center.x, y: self.bounds.height * 0.5, width: btnW, height: btnW)
        
        //设置composeBtn的位置
        composeBtn.bounds.size = CGSize(width: btnW, height: btnH)
        composeBtn.center = CGPoint(x: self.center.x, y: self.bounds.height * 0.5)
    }
    
    
    //通过懒加载实例化微博的按钮
    private lazy var composeBtn : UIButton = {
       let btn = UIButton()
        
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return btn
        
    }()
    
    
}
















